package com.jay.compass.utils;

import com.jay.compass.ble.BluetoothLeService;

import android.os.Handler;

/**
 * Timer, used for count down purposes
 * 
 * @author Administrator
 */
public class BTimer extends Thread {

	private int time;
	public int time_left;
	static private BTimer mTimer;
	private Handler mHandler;
	private boolean isRunning;

	public void setHandler(Handler handler) {
		mHandler = handler;
	}

	private BTimer(int t) {
		time = t;
		isRunning = false;
	}

	public void setTime(int time) {
		this.time = time;
	}

	static public BTimer getInstance() {
		if (mTimer == null) {
			mTimer = new BTimer(BluetoothLeService.SERVICE_INTERVAL);
		}
		return mTimer;
	}

	public void update(int i) {
		time_left = i;
	}

	public void run() {
		isRunning = true;
		time_left = time;
		try {
			while (time_left > 0) {
				BTimer.sleep(1000);
				time_left--;
				if (mHandler != null) {
					mHandler.sendEmptyMessage(time_left);
				}
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		interrupt();
		mTimer = null;
		isRunning = false;
		return;
	}

	public boolean isRunning() {
		return isRunning;
	}

	public int gettimeleft() {
		return time_left;
	}
}